﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

using MyLibrary;

namespace MyLibrary.Net
{
    /// <summary>
    /// 心跳器
    /// </summary>
    public abstract class HeartBeat : DisposeableAndStartableBase
    {
        protected Timer heartbeatChecker;
        int heartbeatPeriod;
        /// <summary>
        /// 心跳频率(毫秒)
        /// </summary>
        public int HeartbeatPeriod
        {
            get { return heartbeatPeriod; }
            set { heartbeatPeriod = value; }
        }

        bool enableHB;
        /// <summary>
        /// 是否启用心跳
        /// </summary>
        public bool EnableHB
        {
            get { return enableHB; }
            set { enableHB = value; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public HeartBeat()
        {
            heartbeatPeriod = 30000;  //默认心跳时间为30秒
        }

        /// <summary>
        /// 开始心跳
        /// </summary>
        protected override void OnStart()
        {
            if (EnableHB)
            {
                {
                    heartbeatChecker = new Timer(new TimerCallback(HeartBeatCallback), null, HeartbeatPeriod, HeartbeatPeriod);
                    NetDebuger.PrintDebugMessage("Start Heartbeat. Peroid:" + HeartbeatPeriod + "(ms)");
                }
            }
        }

        /// <summary>
        /// 停止心跳
        /// </summary>
        protected override void OnStop()
        {
            if (EnableHB && heartbeatChecker != null)
            {
                lock (heartbeatChecker)
                {
                    NetDebuger.PrintDebugMessage("Stop Heartbeat");
                    heartbeatChecker.Dispose();
                    heartbeatChecker = null;
                }
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        protected override void Free(bool disposeByUser)
        {
            if (disposeByUser)
                Stop();
            base.Free(disposeByUser);
        }

        /// <summary>
        /// 心跳检查的回调函数
        /// </summary>
        /// <param name="o">参数</param>
        protected abstract void HeartBeatCallback(object o);
    }
}
